package org.simplecrm.repository.event.eventtype;

import org.simplecrm.domain.event.eventtype.EventType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Oleksandr_Terekh on 9/4/2014.
 */
@Repository("eventTypeDAO")
public class EventTypeJdbcDAO implements EventTypeDAO {

    private static final Logger LOGGER = LoggerFactory.getLogger(EventTypeJdbcDAO.class);

    private static final String SELECT_ALL = "SELECT * FROM EventType";

    private DataSource ds;

    @Autowired
    public EventTypeJdbcDAO(DataSource ds) {
        this.ds = ds;
    }

    @Override
    public List<EventType> getAllEventTypes() {

        List<EventType> eventTypes = new LinkedList<>();

        try (Connection con = ds.getConnection();
             PreparedStatement statement = con.prepareStatement(SELECT_ALL,
                     ResultSet.TYPE_SCROLL_INSENSITIVE,
                     ResultSet.CONCUR_UPDATABLE);
             ResultSet resultset = statement.executeQuery()) {

            while (resultset.next()) {

                EventType eventType = null;

                int id = resultset.getInt(EVENTTYPE_ID_FIELD);
                String name = resultset.getString(EVENTTYPE_NAME_FIELD);

                eventType = new EventType(id, name);

                eventTypes.add(eventType);
            }

        } catch (SQLException ex) {
            LOGGER.error(ex.toString(), ex);
            eventTypes = null;
        }

        return eventTypes;
    }
}
